package cn.nxcoder.blog.controller;

import cn.nxcoder.blog.entity.Comment;
import cn.nxcoder.blog.entity.User;
import cn.nxcoder.blog.service.BlogService;
import cn.nxcoder.blog.service.CommentService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 评论Controller
 * @author shengwu ni
 * @date 2018/05/09 22:28
 */
@Controller
@RequestMapping("/")
public class CommentController {

    @Resource
    private CommentService commentService;
    @Resource
    private BlogService blogService;

    @Value("${comment.avator}")
    private String avator;

    @GetMapping("/comments/{blogid}")
    public String comment(@PathVariable Long blogid, Model model) {
        // 获取所有的评论记录
        List<Comment> comments = commentService.listCommentByBlogId(blogid);
        model.addAttribute("comments", comments);
        return "blog :: commentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            comment.setAvator(user.getAvator());
            comment.setAdminComment(1);
        } else {
            comment.setAvator(avator);
        }
        // 将评论内容中的emoji表情转换一下，否则入库会报错。
        String tmpContent = EmojiParser.parseToAliases(comment.getContent());
        comment.setContent(tmpContent);
        commentService.saveComment(comment);
        return "redirect:/comments/" + comment.getBlogid();
    }

}
